package com.chunxuan.langquan.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.KeyboardUtils;
import com.chunxuan.langquan.MainActivity;
import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.Base2Activity;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Config;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.GradeInfo;
import com.chunxuan.langquan.dao.bean.JsonBean;
import com.chunxuan.langquan.dao.bean.LqProvinceBean;
import com.chunxuan.langquan.dao.bean.UploadImageUrl;
import com.chunxuan.langquan.dao.bean.UserInfo;
import com.chunxuan.langquan.dao.http.APIRetrofit;
import com.chunxuan.langquan.support.util.Base64Util;
import com.chunxuan.langquan.support.util.BitmapUtil;
import com.chunxuan.langquan.support.util.GetJsonDataUtil;
import com.chunxuan.langquan.support.util.GlideUtil;
import com.chunxuan.langquan.support.util.Logg;
import com.chunxuan.langquan.support.util.PermissionUtil;
import com.chunxuan.langquan.support.util.SelectDialog;
import com.chunxuan.langquan.ui.listener.MyOrientationListener;
import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.makeramen.roundedimageview.RoundedImageView;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.ToastUtils;

import org.json.JSONArray;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 个人资料页面
 */
public class PersonalInfoActivity extends Base2Activity {
    private RelativeLayout rlHeader,rlNickName,rlGender,rlRegion,rlGrade;
    private TextView tv_area,tvNickname,tvGender,tvGrade;
    private ImageView ivBack;
    private RoundedImageView rivHeader;
    private List<String> genderList=new ArrayList<>();
    private List<String> gradeList=new ArrayList<>();
    private List<GradeInfo> gradeInfoList=new ArrayList<>();
    private OptionsPickerView genderOptions,gradeOptions,pvOptions;
    private String grade_category_name;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    public static final int EDIT_USER_NICKNAME = 1002;

    private int genderInt;
    private String headerUrl;//上传base64图片后获取到的头像url

    private List<LqProvinceBean> lqProvinceBeanList=new ArrayList<>();
    private String mergename;
    private String pro,city,area;

    //百度地图-获取定位
    private LocationClient mylocationClient;//定位服务客户对象
    private MylocationListener mylistener;//重写的监听类
    private int count=0;
    private MyOrientationListener myOrientationListener;//方向感应器类对象
    private boolean selectLocation=false;
    @Override
    protected int getLayoutRes() {
        return R.layout.activity_my_personal_information;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_my_personal_information);
        rlHeader= findViewById(R.id.rl_personal_info_header);
        rlNickName=findViewById(R.id.rl_personal_info_nick_name);
        rlGender=findViewById(R.id.rl_personal_info_gender);
        rlRegion=findViewById(R.id.rl_personal_info_region);
        rlGrade=findViewById(R.id.rl_personal_info_grade);
        tv_area=findViewById(R.id.tv_area);
        ivBack=findViewById(R.id.menu_back);
        tvNickname=findViewById(R.id.tv_nickname);
        tvGender=findViewById(R.id.tv_gender);
        tvGrade=findViewById(R.id.tv_grade);
        rivHeader=findViewById(R.id.iv_header);

        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (!permissionList.isEmpty()) {
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(this, permissions, 1);
        }
        initLocation();

        Intent intent=getIntent();
        if(null!=intent){
            mergename = intent.getStringExtra("mergename");
            if(!TextUtils.isEmpty(mergename)){
                String[] mergenameList=mergename.split(",");
                pro=mergenameList[1];
                city=mergenameList[2];
                area=mergenameList[3];
//                tvSelectCity.setText(mergename.replace("中国","").replaceAll(",",""));
                selectLocation=true;
                tv_area.setText(pro+city+area);
                editArea();
            }
            String area1=intent.getStringExtra("area");
            if(!TextUtils.isEmpty(area1)){
                tv_area.setText(area1);
            }
            String avatar=intent.getStringExtra("avatar");
            if(!TextUtils.isEmpty(avatar)){
                GlideUtil.loadImg(avatar,rivHeader);
            }
            String nickname=intent.getStringExtra("nickname");
            int gender=intent.getIntExtra("gender",0);
            String grade_category_name=intent.getStringExtra("grade_category_name");
            tvNickname.setText(nickname);
            if(gender==0){
                tvGender.setText("保密");
            }else if(gender==1){
                tvGender.setText("男");
            }else if(gender==2){
                tvGender.setText("女");
            }
            tvGrade.setText(grade_category_name);
        }
        getProvList();
        getGradeInfo();
        genderList.add("保密");
        genderList.add("男");
        genderList.add("女");
        setOnClickListener(rlHeader,rlNickName,rlGender,rlRegion,rlGrade,ivBack);
    }

    private void initLocation() {
        //定位服务的客户端。宿主程序在客户端声明此类，并调用，目前只支持在主线程中启动
        mylocationClient = new LocationClient(this);
        mylistener = new MylocationListener();

        //注册监听器
        mylocationClient.registerLocationListener(mylistener);
        //配置定位SDK各配置参数，比如定位模式、定位时间间隔、坐标系类型等
        LocationClientOption mOption = new LocationClientOption();
        //设置坐标类型
        mOption.setCoorType("bd09ll");
        //设置是否需要地址信息，默认为无地址
        mOption.setIsNeedAddress(true);
        //设置是否打开gps进行定位
        mOption.setOpenGps(true);
        //设置扫描间隔，单位是毫秒 当<1000(1s)时，定时定位无效
        int span = 2000;
        mOption.setScanSpan(span);
        //设置 LocationClientOption
        mylocationClient.setLocOption(mOption);

        myOrientationListener = new MyOrientationListener(PersonalInfoActivity.this);
    }
    /*
     *定位请求回调接口
     */
    public class MylocationListener implements BDLocationListener {
        //定位请求回调函数,这里面会得到定位信息
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            //BDLocation 回调的百度坐标类，内部封装了如经纬度、半径等属性信息
            //MyLocationData 定位数据,定位数据建造器
            /*
             * 可以通过BDLocation配置如下参数
             * 1.accuracy 定位精度
             * 2.latitude 百度纬度坐标
             * 3.longitude 百度经度坐标
             * 4.satellitesNum GPS定位时卫星数目 getSatelliteNumber() gps定位结果时，获取gps锁定用的卫星数
             * 5.speed GPS定位时速度 getSpeed()获取速度，仅gps定位结果时有速度信息，单位公里/小时，默认值0.0f
             * 6.direction GPS定位时方向角度
             * */
            count++;
//            Log.e("==位置==",bdLocation.getProvince()+"-"+bdLocation.getCity()+"-"+bdLocation.getDistrict()+"-"+bdLocation.getStreet());
            if(!TextUtils.isEmpty(bdLocation.getProvince())&&!TextUtils.isEmpty(bdLocation.getCity())&&!TextUtils.isEmpty(bdLocation.getDistrict())){
                Arad.preferences.putString(Config.PROVINCE, bdLocation.getProvince()).flush();
                Arad.preferences.putString(Config.CITY, bdLocation.getCity()).flush();
                Arad.preferences.putString(Config.AREA, bdLocation.getDistrict()).flush();
                if(selectLocation){
                    return;
                }
//                else{
//                    pro=bdLocation.getProvince();
//                    city=bdLocation.getCity();
//                    area=bdLocation.getDistrict();
//                    tvSelectCity.setText(bdLocation.getProvince()+bdLocation.getCity()+bdLocation.getDistrict());
//                }
            }
        }
    }
    /*
     *定位服务的生命周期，达到节省
     */
    @Override
    protected void onStart() {
        super.onStart();
        //开启定位，显示位置图标
        if(!mylocationClient.isStarted()){
            mylocationClient.start();
        }
        myOrientationListener.start();
    }
    @Override
    protected void onStop() {
        super.onStop();
        mylocationClient.stop();
        myOrientationListener.stop();
    }

    private void editArea() {
        APIRetrofit.getDefault().editArea(Global.HEADER, pro,city,area)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 result2) throws Exception {
                        hideProgress();
                        ToastUtils.showShort(result2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("修改地区失败");
                    }
                });
    }
    private void getGradeInfo() {
        APIRetrofit.getDefault().getGradeInfo(Global.HEADER, "")
                .compose(RxUtil.<BaseResult2<List<GradeInfo>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<GradeInfo>>>() {
                    @Override
                    public void accept(BaseResult2<List<GradeInfo>> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            if(null!=result2.getData()&&result2.getData().size()>0){
                                gradeInfoList=result2.getData();
                                for(int t=0;t<gradeInfoList.size();t++){
                                    gradeList.add(gradeInfoList.get(t).getName());
                                }
                            }
                        }else{
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取年级列表失败");
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rl_personal_info_header:
                selectHeader();
                break;
            case R.id.rl_personal_info_nick_name:
                Intent intent=new Intent(this,EditUserNicknameActivity.class);
                intent.putExtra("nickname",tvNickname.getText().toString().trim());
                startActivityForResult(intent,EDIT_USER_NICKNAME);
                break;
            case R.id.rl_personal_info_gender:
                showGenderPickerView();
                break;
            case R.id.rl_personal_info_region:
//                KeyboardUtils.hideSoftInput(this);
//                initJsonData();
//                ShowPickerView();
                Bundle bundle = new Bundle();
                bundle.putSerializable("lqProvinceBeanList", (Serializable) lqProvinceBeanList);
                bundle.putString("from","个人信息");
                Intent intent1 = new Intent(PersonalInfoActivity.this, SelectProvinceActivity.class);
                intent1.putExtras(bundle);
                startActivity(intent1);
                break;
            case R.id.rl_personal_info_grade:
                showGradePickerView();
                break;
            case R.id.menu_back:
                Intent intent2 = new Intent(PersonalInfoActivity.this, MainActivity.class);
                intent2.putExtra("guid_id", 3);
                startActivity(intent2);
                finish();
                break;
        }
    }
    private Disposable getProvList() {
        return APIRetrofit.getDefault().getProvList(Global.HEADER,"")
                .compose(RxUtil.<BaseResult2<List<LqProvinceBean>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<LqProvinceBean>>>() {
                    @Override
                    public void accept(BaseResult2<List<LqProvinceBean>> result2) throws Exception {
                        hideProgress();
                        if(result2.isSuccess()){
                            lqProvinceBeanList=result2.getData();
                        }else{
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取省份列表失败");
                    }
                });
    }
    private void showGradePickerView() {
        gradeOptions=new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String grade=gradeInfoList.get(options1).getName();
                tvGrade.setText(grade);
                grade_category_name=grade;
                editGrade(gradeInfoList.get(options1).getId());
            }
        }).setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = v.findViewById(R.id.tv_confirm);
                TextView ivCancel = v.findViewById(R.id.iv_cancel);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        gradeOptions.returnData();
                        gradeOptions.dismiss();
                    }
                });

                ivCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        gradeOptions.dismiss();
                    }
                });
            }
        })
                .setOutSideCancelable(false)
                .setTitleText("")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        gradeOptions.setPicker(gradeList);
        gradeOptions.show();
    }

    private void editGrade(int grade_category_id) {
        APIRetrofit.getDefault().editGrade(Global.HEADER, grade_category_id)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 result2) throws Exception {
                        hideProgress();
                        ToastUtils.showShort(result2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("修改年级失败");
                    }
                });
    }

    private void selectHeader() {
        final List<String> names = new ArrayList<>();
        names.add("拍照");
        names.add("从手机相册选择");
//        names.add("取消");
        PermissionUtil.handleMultiPermission(this, "读写",
                new PermissionUtil.PermissionListener() {
                    @Override
                    public void onPermissionOk(boolean isOk) {
                        if (isOk) {
                            showDialog3(new SelectDialog.SelectDialogListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    switch (position) {
                                        case 0: // 直接调起相机
                                            /**
                                             * 0.4.7 目前直接调起相机不支持裁剪，如果开启裁剪后不会返回图片，请注意，后续版本会解决
                                             *
                                             * 但是当前直接依赖的版本已经解决，考虑到版本改动很少，所以这次没有上传到远程仓库
                                             *
                                             * 如果实在有所需要，请直接下载源码引用。
                                             */
                                            //打开选择,本次允许选择的数量
//                                                    ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                                            ImagePicker.getInstance().setSelectLimit(1);
                                            Intent intent = new Intent(PersonalInfoActivity.this, ImageGridActivity.class);
                                            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                            startActivityForResult(intent, REQUEST_CODE_SELECT);
                                            break;
                                        case 1:
                                            //打开选择,本次允许选择的数量
                                            ImagePicker.getInstance().setSelectLimit(1);
                                            Intent intent1 = new Intent(PersonalInfoActivity.this, ImageGridActivity.class);
                                            /* 如果需要进入选择的时候显示已经选中的图片，
                                             * 详情请查看ImagePickerActivity
                                             * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                                            startActivityForResult(intent1, REQUEST_CODE_SELECT);
                                            break;
//                                        case 2:
//
//                                            break;
                                        default:
                                            break;
                                    }

                                }
                            }, names);
                        } else {
                            ToastUtils.showShort("权限不足");
                        }
                    }

                    @Override
                    public void onOpenPermissionPage(boolean isOpen) {

                    }
                }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
    private SelectDialog showDialog3(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }
    ArrayList<ImageItem> images = null;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null&&images.size()>0) {
//                        File file= new File(images.get(0).uri.getPath());
                    String base64Pic= "data:image/png;base64,"+Base64Util.imageToBase64(images.get(0).uri.getPath());
                    uploadPic(base64Pic);
                }
            } else {
                ToastUtils.showShort("请选择图片");
            }
        }else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                }
            }
        }else if(resultCode==EDIT_USER_NICKNAME){
            String newNickname=data.getStringExtra("new_nickname");
            tvNickname.setText(newNickname);
            tvNickname.setVisibility(View.VISIBLE);
        }
    }
    private Disposable uploadPic(String base64Pic) {
        return APIRetrofit.getDefault().uploadBase64(Global.HEADER,base64Pic)
                .compose(RxUtil.<BaseResult2<UploadImageUrl>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<UploadImageUrl>>() {
                    @Override
                    public void accept(BaseResult2<UploadImageUrl> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            Logg.e("==上传头像图片=="+result2.getData().getUrl());
                            headerUrl=result2.getData().getUrl();
                            GlideUtil.loadImg(headerUrl,rivHeader);
                            editHeader(headerUrl);
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("上传图片失败");
                    }
                });
    }

    private void editHeader(String avatar) {
        APIRetrofit.getDefault().editHeader(Global.HEADER, avatar)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 result2) throws Exception {
                        hideProgress();
                        ToastUtils.showShort(result2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("修改用户头像失败");
                    }
                });
    }

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private void initJsonData() {//解析数据
//         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
//         * 关键逻辑在于循环体
        String JsonData = new GetJsonDataUtil().getJson(this, "city.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

//         * 添加省份数据
//         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
//         * PickerView会通过getPickerViewText方法获取字符串显示出来。
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getAreaList() == null || jsonBean.get(i).getCityList().get(c).getAreaList().size() == 0) {
                    City_AreaList.add("");
                } else {
                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getAreaList().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getAreaList().get(d).getName();
                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }
            //添加城市数据
            options2Items.add(CityList);
            //添加地区数据
            options3Items.add(Province_AreaList);
        }
    }
    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }
    private void showGenderPickerView() {
        genderOptions=new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String gender=genderList.get(options1);
                tvGender.setText(gender);
                if(gender.contains("保密")){
                    genderInt=0;
                }else if(gender.contains("男")){
                    genderInt=1;
                }else if(gender.contains("女")){
                    genderInt=2;
                }
                editGender(genderInt);
            }
        }).setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = v.findViewById(R.id.tv_confirm);
                TextView ivCancel = v.findViewById(R.id.iv_cancel);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        genderOptions.returnData();
                        genderOptions.dismiss();
                    }
                });

                ivCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        genderOptions.dismiss();
                    }
                });
            }
        })
                .setOutSideCancelable(false)
                .setTitleText("")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        genderOptions.setPicker(genderList);
        genderOptions.show();
    }

    private void editGender(int genderInt) {
        APIRetrofit.getDefault().editGender(Global.HEADER, genderInt)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 result2) throws Exception {
                        hideProgress();
                        ToastUtils.showShort(result2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("修改性别失败");
                    }
                });
    }

    private void ShowPickerView() {// 弹出选择器
        pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String opt1tx = options1Items.size() > 0 ? options1Items.get(options1).getPickerViewText() : "";
                String opt2tx = options2Items.size() > 0 && options2Items.get(options1).size() > 0 ? options2Items.get(options1).get(options2) : "";
                String opt3tx = options2Items.size() > 0 && options3Items.get(options1).size() > 0 && options3Items.get(options1).get(options2).size() > 0 ? options3Items.get(options1).get(options2).get(options3) : "";

                String tx = opt1tx + opt2tx + opt3tx;
                String addr = tx;
                tv_area.setVisibility(View.VISIBLE);
                if(addr.length()>10&&addr.length()<=16){
                    tv_area.setTextSize(14);
                }if(addr.length()>16){
                    tv_area.setTextSize(12);
                }else{
                    tv_area.setTextSize(16);
                }
                tv_area.setText(addr);
            }
        }).setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = v.findViewById(R.id.tv_confirm);
                TextView ivCancel = v.findViewById(R.id.iv_cancel);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvOptions.returnData();
                        pvOptions.dismiss();
                    }
                });

                ivCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvOptions.dismiss();
                    }
                });
            }
        })
                .setOutSideCancelable(false)
                .setTitleText("")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }
}

